package com.probiz.estore.imports.handler.customer;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.probiz.estore.common.model.customer.Customer;
import com.probiz.estore.customer.service.CustomerManager;
import com.probiz.estore.imports.handler.ColumnHandler;
import com.probiz.estore.imports.handler.basic.ColumnBasicHandler;
import com.probiz.estore.imports.model.Column;
import com.probiz.estore.imports.model.ImportModel;

public class UsernameHandler extends ColumnBasicHandler implements ColumnHandler {
	private Logger logger = Logger.getLogger(UsernameHandler.class);
	
	private CustomerManager customerManager;

	public void setCustomerManager(CustomerManager customerManager) {
		this.customerManager = customerManager;
	}

	public void setProperty(ImportModel importModel, Column column)	throws Exception {
		String value = column.getValue();
		if(StringUtils.isBlank(value)){
			//设置结果
			importModel.setResult(ImportModel.RESULT_ERROR);
			String msg = "账号为空，无法导入";
			logger.error(msg);
			importModel.setMsg(msg);
			return;
		} else {
			Pattern p = Pattern.compile("^[\\w-\\d]+$");
	    	Matcher m = p.matcher(value);
			if(value.length()<5 || value.length()>20){
				importModel.setResult(ImportModel.RESULT_ERROR);
				String msg = "账号: "+value+" 不正确，账号长度必须大于或等于5，小于20";
				logger.error(msg);
				importModel.setMsg(msg);
				return;
			} else if(!m.matches()){
				importModel.setResult(ImportModel.RESULT_ERROR);
				String msg = "账号: "+value+" 不正确，账号只能由字母、数字、下划线、减号等字符组成。";
				logger.error(msg);
				importModel.setMsg(msg);
				return;
			}
		}
		value = value.trim();
		Customer customer = customerManager.getCustomerByUsername(value);
		if(null == customer){
			customer = new Customer();
			importModel.setUpdate(false);
		}else{
			importModel.setUpdate(true);
		}
		customer.setUsername(value);
		//设置target
		importModel.setTarget(customer);
		//设置结果
		importModel.setResult(ImportModel.RESULT_SUCCESS);
		
	}

}
